<script setup>
import { reactive, ref } from 'vue'
import { userLoginAPI } from '@/apis/userAPI.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore} from '@/stores/user'
const router=useRouter();
const userStore=useUserStore();

const captchaCode = ref('') // 生成的随机验证码
const loading = ref(false)
const loginFormRef = ref()
const loginForm=reactive({
  account:'',
  password:'',
  userCaptcha:''
})
// 生成随机验证码（4位字母数字混合，排除易混淆字符）
const generateCaptcha = () => {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaCode.value = code
}

// 页面加载时生成初始验证码
generateCaptcha()
const rules = {
  account: [
    { required: true, message: '用户名不能为空',trigger:'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空' },
    { min: 6, max: 14, message: '密码长度要求6-14个字符' },
    // { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*?&]{6,14}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  userCaptcha:[
    {required: true, message: '验证码不能为空'}
  ]
}
const handleLogin = async () => {
   const valid = await loginFormRef.value.validate();
    if (!valid) return;
    loading.value = true
    try {
      // TODO: 调登录接口,token是属性，rolesLogo是数组属性

      const {data}=await userLoginAPI(loginForm)
      const { token ,roleLogos,user}=data;
      userStore.setToken(token,user,roleLogos)
       if(roleLogos?.includes('ADMIN')){
         router.push('/home')
         ElMessage.success('登录成功')
      }else if(roleLogos?.includes('DISPATCHER')){
        router.push('/userHome')
        ElMessage.success('登录成功')
      }else{
        ElMessage.error("无权限")
      }
    } catch {
      ElMessage.error('登录失败')
      generateCaptcha() // 刷新验证码
    } finally {
      loading.value = false
    }
}
</script>
<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>工单管理系统</h2>
        <p>请登录您的账号</p>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" @keyup.enter="handleLogin" class="login-form"  label-width="80px">
        <el-form-item label="用户名" prop="account">
          <el-input v-model="loginForm.account"/>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password" label="密码">
          <el-input v-model="loginForm.password" type="password" show-password :prefix-icon="Lock"/>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="userCaptcha" label="验证码">
           <el-input v-model="loginForm.userCaptcha" placeholder="请输入验证码" maxlength="4" size="large">
    <!-- 验证码放在 suffix 插槽里 -->
            <template #suffix>
              <div class="captcha-code" @click="generateCaptcha">{{ captchaCode }}</div>
            </template>
           </el-input>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" size="large" style="width: 100%" @click="handleLogin" :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>



<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 800px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-card {
  width: 380px;
  padding: 3rem;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 2rem;
}

.login-header h2 {
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 1.8rem;
}

.login-header p {
  color: #666;
  font-size: 0.9rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-label {
  display: block;
  margin-bottom: 0.5rem;
  color: #555;
  font-weight: 500;
}

.input-wrapper {
  position: relative;
}

.icon-user, .icon-lock, .icon-code {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

/* 验证码图标样式 */
.icon-code {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='16' height='16' fill='none' stroke='currentColor' stroke-width='2'%3E%3Crect x='3' y='11' width='18' height='11' rx='2' ry='2'/%3E%3Cpath d='M7 11V7a5 5 0 0 1 10 0v4'/%3E%3C/svg%3E");
  width: 16px;
  height: 16px;
  background-repeat: no-repeat;
}

input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

/* 验证码输入框特殊样式 */
#captcha {
  padding-right: 120px; /* 给右侧验证码预留空间 */
}

input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

/* 验证码显示区域样式 */
.captcha-code {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
  width: 100px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #333;
  font-weight: bold;
  letter-spacing: 4px;
  cursor: pointer;
  user-select: none;
  font-size: 16px;
  padding: 0 8px;
  box-shadow: 0 0 5px rgba(0,0,0,0.1);
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-btn:hover {
  opacity: 0.9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}
</style>
